#-*- coding:utf8 -*-
'''기준정보'''

__author__ = 'jh,Seo'
__version__ = '0.1'

from django.core.servers.basehttp import FileWrapper
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.template import Context, RequestContext
from django.shortcuts import render_to_response
from django.template.loader import get_template
from django.contrib.auth.models import User
from django.contrib.auth import logout
from django.core.mail import send_mail

from forms import ProjectCreateForm, LoginForm, CodeCreateForm, UserInformationForm
import logging
log = logging.getLogger(__name__)
from models import *
from django.db.models import Q

from django.contrib.auth.decorators import login_required


from django.contrib.auth import authenticate
from django.contrib.auth import login as auth_login

from django.core import serializers
from django.utils import simplejson


import base64

def login(request):
    '''LOGIN'''

    redirect_to = request.REQUEST.get('redirect_to', '/') #로그인 이후에 이동할 페이지
    logging.info(redirect_to)

    if request.method == 'POST':
        form = LoginForm(request.POST)
        logging.info(request.POST)

        user = authenticate(
            username=request.POST['username'],
            password=request.POST['password']
        )


        if user is not None:
            if user.is_active:

                logging.info("사용자이름과 비밀번호가 일치했습니다!")

                auth_login(request, user)

                # load session object
                profile = UserProfiles.objects.get(user=user)
                request.session['profile'] = profile
                

                return HttpResponseRedirect(redirect_to)

            else:
                print "사용자 계정이 중단되었습니다!"
        else:
            variables = RequestContext(request, {
                    'form':form,
                    'redirect_to':redirect_to,
                    'msg':'-_-'
                }
            )

            return render_to_response('registration/login.html', variables)

    else:
        form = LoginForm()
        #logging.info(form)
        variables = RequestContext(request, {
            'form':form,
            'redirect_to':redirect_to
            })

        return render_to_response('registration/login.html', variables)

def project_create(request):
    logging.info("@@@@@@@@@@@@@@@")

    if request.method == 'POST':
        form = ProjectCreateForm(request.POST)

        if form.is_valid():
            logging.info(form.cleaned_data['project_code'])
            logging.info(form.cleaned_data['project_desc'])
            logging.info(form.cleaned_data['client_company'])
            logging.info(form.cleaned_data['ordering_company'])
            logging.info(form.cleaned_data['deposit'])
            logging.info(form.cleaned_data['contract_date'])
            logging.info(form.cleaned_data['complete_date'])

            #project = Project (instance=form)
            project = Project()
            project.project_code = form.cleaned_data['project_code']
            project.project_desc = form.cleaned_data['project_desc']
            project.client_company = form.cleaned_data['client_company']
            project.ordering_company = form.cleaned_data['ordering_company']
            project.deposit = form.cleaned_data['deposit']
            project.contract_date = form.cleaned_data['contract_date']
            project.complete_date = form.cleaned_data['complete_date']
            #project.super_project_code = form.cleaned_data['super_project_code']

            #project.cdate = form.cleaned_data['cdate']
            #project.udate = form.cleaned_data['udate']
            #project.ddate = form.cleaned_data['ddate']





            logging.info(project)

            project.save()
            return HttpResponseRedirect('/register/success/')

        else:
            variables = RequestContext(request, {
                'form':form
                })

            return render_to_response('master/project_create.html', variables)
    else:
        #form = CreateProjectForm(initial={'project_code':'@@@'})
        form = ProjectCreateForm()
        variables = RequestContext(request, {
            'form':form,
            'foo':'@@@'
            })
        return render_to_response('master/project_create.html', variables)


def project_info(request, project_code):
    '''
    프로젝트 상세'''

    project = Project.objects.get(project_code=project_code)

    variables = RequestContext(request, {
        'object':project
        })
    return render_to_response('master/project_info.html', variables)


@login_required(redirect_field_name='redirect_to')
def project_list(request):
    '''project lists
    '''

    #print request.session['user']
    #print request.session['foo']
    
    profile = request.session['profile']
    
    #projects = Project.objects.all()
    company_code = profile.dept.company.company_code
    log.info('company_code = ' + company_code)
    projects = Project.objects.filter(company=profile.dept.company)

    variables = RequestContext(request, {
        'object':projects
        })
    return render_to_response('master/project_list.html', variables)




@login_required(redirect_field_name='redirect_to')
def code_list(request, data=None):
    '''코드목록'''

    log.info("######################")
    #print 'from View = ' + request.session['django_language']
    
    from django.utils.translation import ugettext as _
    #import locale
    #locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
    
    print ("-_- " +  _('Hello'))
    
    
    #log.info(request.session.get('profile').tel_no)

    #logging.info(data)
    #logging.info(base64.decodestring(data))

    group_code = None
    upper_code = None
    complete = None

    group_code = request.session.get('profile').dept.company.group.code


    if data is not  None:
        logging.debug("낫논")
        param = base64.decodestring(data)
        logging.debug("param = " + param)

        exec("param=" + param)



        '''
        if param.has_key('house_code'):
            house_code = param['house_code']
        '''
        if param.has_key('upper_code'):
            upper_code = param['upper_code']
        if param.has_key('complete'):
            complete=param['complete']

    else:
        log.debug("이건 아닌데...")


    codes = None
    if upper_code is not None:
        log.debug("왜 또 이러냐? 1")
        log.debug(
                GroupCodes.objects.filter(group=Groups.objects.get(code=group_code),
                    code=upper_code)
                )

        upperCode = GroupCodes.objects.filter(
                group=Groups.objects.get(code=group_code),
                code=upper_code)

        if len(upperCode) > 0:
            codes = GroupCodes.objects.filter(
                    group=Groups.objects.get(code=group_code),
                    upper_code=upperCode).order_by('code', 'sort_seq')
        else:
            codes = []
    else:
        logging.debug("왜 또 이러냐? 2")
        
        codes = GroupCodes.objects.filter(
                group=Groups.objects.get(code=group_code),
                upper_code=None).order_by('code', 'sort_seq')
        #else:
        #codes = MasterCode.objects.filter(super_code=super_code).order_by('house_code', 'code', 'sort_seq')
     #   codes = None

    variables = RequestContext(request, {
        'list':codes,
        'group_code':group_code,
        'upper_code':upper_code,
        'complete':complete
        })
    return render_to_response('master/code_list.html', variables)



def code_info(request, code=None):
    '''코드상세'''

    object= GroupCodes.objects.get(code=base64.decodestring(code))
    child_object = GroupCodes.objects.filter(upper_code=object)

    variables = RequestContext(request, {
        'object':object,
        'child_object':child_object
        })

    if request.REQUEST.get("requestType") == None:
        #if request.REQUEST['requestType'] !=  None:
    #if request.REQUEST["requestType"] != 'layer':
    #if request.is_ajax() == True:
        return render_to_response('master/code_info.html', variables)
    else:
        return render_to_response('master/ajax.code_info.html', variables)
    #return render_to_response('master/code_info.html', variables)

def code_edit(request, code=None):
    '''코드 수정'''
    form = None

    #masterCode = MasterCode.objects.filter(code=base64.decodestring(code))[0]
    if request.method == 'GET':
        masterCode = MasterCode.objects.filter(code=base64.decodestring(code))[0]
        logging.info(masterCode)

        form = CodeCreateForm(instance=masterCode, house_code='100')

    elif request.method == 'POST':
        m = MasterCode.objects.filter(code=request.POST['code'])[0]
        form = CodeCreateForm(request.POST, house_code='100',
                instance=m)

        if form.is_valid():
            form.save()




            foo = request.POST.get('foo', False)
            if foo:
                masterCode = MasterCode.objects.filter(code=request.POST['foo'])[0]
                m = MasterCode.objects.filter(code=form.cleaned_data['code'])[0]

                m.save()

            else:
                None
                #masterCode = None




        #logging.debug(form)





    variables = RequestContext(request, {
        'form':form
        })

    return render_to_response('master/code_edit.html', variables)



def code_create(request):
    '''코드생성'''

    if request.method == 'GET':
        logging.info("--- get ---");
        form = CodeCreateForm(house_code='100')


    else:
        logging.info("--- post ---");
        '''
        if request.POST['used'] == None:
            form.used = False
        else:
            form.used = True
        '''
        #masterCode = MasterCode.objects.get(pk=request.POST['super_code'])
        foo = request.POST.get('foo', False)

        log.debug(foo)

        if foo:
            masterCode = MasterCode.objects.filter(code=request.POST['foo'])[0]
            groupCode = GroupCode.objects.filter()
        else:
            masterCode = None

        #logging.debug(masterCode)
        #form.super_code = masterCode

        form = CodeCreateForm(request.POST, house_code=request.POST['house_code'])

        if form.is_valid():
            logging.debug("******************************")
            logging.debug(form.fields)
            logging.debug(masterCode)
            #form.fields["super_code"].queryset = masterCode
            logging.debug("******************************")
            form.save()

            m = MasterCode.objects.filter(code=form.cleaned_data['code'])[0]
            m.super_code = masterCode
            m.save()

        else:
            logging.info(form)
            logging.debug("아시발")

        logging.info("******* END ************************")



    variables = RequestContext(request, {
        'form':form
        })

    return render_to_response('master/code_create.html', variables)




@login_required(redirect_field_name='redirect_to')
def dept_tree(request):
    '''부서트리'''

    variables = RequestContext(request, {})


    return render_to_response('master/dept_tree.html', variables)


def dept_ajax(request):

    log.info("^^^^^^^^^^^^^^^^^^^^^^")
    

    operation = request.REQUEST["operation"]

    logging.info("operation = " + operation)

    data = None
    if operation == 'get_child':
        super_dept_code = request.REQUEST["super_dept_code"]

        #?operation=get_child&super_dept_code=

        log.info('super_dept_code=' + super_dept_code)

        dao = DeptDao()
        '''data = dao.get_dept_json(ses.get('house_code'),
                                 ses.get('company_code'),
                                 super_dept_code)'''

        data = dao.get_dept_json('100',
                'CC01',
                super_dept_code)

        logging.info("ok")
        #json_serializer = serializers.get_serializer("json")()
        #logging.info("ok2")
        #json_serializer.serialize(data, ensure_ascii=False, stream=response)
        #json_serializer.serialize(data, ensure_ascii=False)
        #a = json_serializer.serialize(data)

    elif operation == 'search':

        dao = DeptDao()
        data = dao.get_child_node(request.REQUEST['search_str'])

    return HttpResponse(
            simplejson.dumps(data),
            content_type = 'application/json; charset=utf8'
            )

def code_select(request):

    description = request.REQUEST.get("term", False);
    logging.debug("description=" + description)
    '''
    Poll.objects.get(
    Q(question__startswith='Who'),
    Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6))
)
    '''
    if description:
        #m = MasterCode.objects.filter(description__startswith=description)
        m = GroupCodes.objects.filter(Q(description__startswith=description) |
                Q(code__startswith=description)
                )
    else:
        m = GroupCodes.objects.all()

    logging.debug(m)

    o = []
    for i in m:

        k = {"code":i.code, "label":i.description}

        o.append(k)

    logging.info(o)
    logging.info("ok")

    return HttpResponse(
            simplejson.dumps(o),
            content_type = 'application/json; charset=utf8'
            )


def customer_list(request):
    '''고객사 목록'''
    variables = RequestContext(request, {})
    return render_to_response('master/customer_list.html', variables)




def foo(request):
    variables = RequestContext(request, {
        })

    dao = DeptDao()
    dao.add_dept()

    return render_to_response('mobile/a.html', variables)

def foo_b(request):
    variables = RequestContext(request, {
        })

    return render_to_response('mobile/b.html', variables)



@login_required(redirect_field_name='redirect_to')
def user_info(request, username):
    '''User detail information.
    It'll be moved when you don't have session information.
    '''
    profile = request.session['profile']
    #form = UserInformationForm()
    
    #log.info('#### >>>>> ' + request.session['profile'].user.username)
    #log.info('#### >>>>> ' + request.session['profile'].tel_no)
    #log.info('#### >>>>> ' + profile.picture)
    if profile.picture is None:
        log.debug("없으면 없다고 하던가")
    
    
    if request.method == 'GET':
        #send_mail(subject, message, from_email, recipient_list, fail_silently=False, auth_user=None, auth_password=None, connection=None)
        #send_mail('from django', 'django', 'ok49@myopera.com', ['jongdal1230@hotmail.com',])
         
        logging.info("--- get ---");
        form = UserInformationForm()
        print '$$$$$$$$$'
        print profile.picture
        print '$$$$$$$$$'
        form.picture = profile.picture
        
    elif request.method == 'POST':
        
        print request.POST
        print request.FILES
        print profile
        
        form = UserInformationForm(request.POST, request.FILES, instance=profile)
        if form.is_valid():
            print '#1'
            print '#2'
            print '#3'
            ha = handle_uploaded_file(request.FILES['picture'])
            #logging.error('### = ' + str(ha))
            #form.cleaned_data['picture'] = '-_-'
            instance = form.save()
            instance.picture = ha
            instance.save()
        else:
            logging.error('WTH!')
    else:
        None
    
    return render_to_response("master/user_info.html",
                              RequestContext(request, {
                                    'form':form,
                                    'profile':profile
                                })
                              )

def picture(request, file_code):
    import os
    import mimetypes
    from django.utils.encoding import smart_str, smart_unicode
    
    path = "WorkManager/resources/"
    file = file_code
    filepath = os.path.join(path,file)

    f = open(filepath , 'rb')
    wrapper = FileWrapper(f)
    response = HttpResponse(wrapper, mimetype=mimetypes.guess_type('picture.jpg'))
    response['Content-Length'] = os.path.getsize(filepath)
    #response['Content-Disposition'] = 'attachment; filenameame={0}'.format('picture.jpg')
    return response

def handle_uploaded_file(file):
    if file:
        import time, sha
        
        t = str(time.time() * 1000)
        ha = sha.new(t).hexdigest()
        
        logging.error("It's a file!")
        logging.error('hash code = %s', str(ha))
        destination = open('WorkManager/resources/' + ha, 'wb+')
        for chunk in file.chunks():
            destination.write(chunk)
        destination.close()
        
        return ha
    
        '''
        destination = open('/tmp/'+file.name, 'wb+')
        #destination = open('/tmp', 'wb+')
        for chunk in file.chunks():
            destination.write(chunk)
        destination.close()
        '''
